package service;

import dao.ShiroDAO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.Menu;
import pojo.User;

import java.util.List;

@Service
public class ShiroService {
    @Autowired
    private ShiroDAO shiroDAO;

    public User doLogin(String userName, String password) throws Exception {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            subject.login(token);//执行登录
            Session session = subject.getSession();
            User user = (User) session.getAttribute("user");
            return user;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            throw new Exception("用户名或密码错误");
        }
    }

    public User getUserByUserName(String userName) {
        return shiroDAO.getUserByUserName(userName);
    }

    public List<String> getUserMenu(String userName) {
//        List<String> roles = shiroDAO.getRoleByUserName(userName);
//        if (roles != null) {
//            for (String role : roles) {
//                List<String> menus = shiroDAO.getPermsByRoleName(role);
//            }
//        }
        return shiroDAO.getUserPermsByUserName(userName);
    }

    public List<String> getRoleByUserName(String userName) {
        return shiroDAO.getRoleByUserName(userName);
    }

    public List<Menu> getMenuPerms() {
        return shiroDAO.getMenuPerms();
    }
}
